import pandas as pd
import tqsdk as ts
import numpy as np
from tqsdk import TqApi, TqAuth

# 创建API实例,传入自己的信易账户
# 初始化SDK
api = ts.TqApi(auth=TqAuth("15842676013@m.com", "482737900Wtxdy"))

# 获取v2401合约信息  
symbol = "DCE.v2401"
contract = api.get_quote(symbol)

# 设置参数  
duration = 60 * 60 * 24  # K线周期：日线  
bar_count = 30  # 均线计算周期：30日  
break_value = 50  # 突破的值：假设为50
boll_window = 20  # BOLL线窗口大小：假设为20
macd_window = 10  # MACD窗口大小：假设为10
alpha = 0.1  # 指数加权移动平均的平滑因子

# 获取历史K线数据
k_lines = api.get_kline_serial(symbol, duration, bar_count)

print(k_lines)

# 计算BOLL线和MACD指标
k_lines["boll"] = k_lines["close"].rolling(window=boll_window).std()*1.02
boll_mid = k_lines["boll"].rolling(window=2*boll_window).mean()
# k_lines["boll_mid"] = boll_mid
df = pd.DataFrame(k_lines["close"])
df["ewm"] = df.ewm(alpha=alpha).mean()
df["macd"], df["macd_signal"], df["macd_hist"] = df["ewm"].diff(), df["ewm"].diff().shift(-1), df["ewm"].diff() - df["ewm"].shift(1)
df["macd"] = df[["macd"]].fillna(0)
df["macd_cross"] = np.where(df["macd"] > df["macd_signal"], 1, -1)

# 判断是否满足条件并生成交易信号
df["trade_signal"] = np.where((df["close"] < df["boll_mid"]) & (df["macd_cross"] == 1), 1, 0)
df["trade_signal"] = np.where((df["close"] > df["boll_mid"]) & (df["macd_cross"] == -1), -1, df["trade_signal"])

# 打印结果
print(df)
# 打印结果
print(k_lines)
# 关闭SDK连接  
api.close()